class CompanyService
  
  # 添加公司
  def self.add(json)
    !Company.create(
        name: json[:name],
        phone_no: json[:phone_no],
        postal_code: json[:postal_code],
        address: json[:address],
        followup_employee_code: json[:followup_employee_code]
    ).new_record?
  end

  # 根据公司id查询公司信息
  def self.query_by_id(id)
    company = Company.find_by('id': id)
    format_company(company)
  end

  def self.page_query(page = 1, per_page = 10)
    logger = LogUtil.new(path: "log/trevor-exam-api.log")
    logger.info('company_service#page_query', "params page=#{ page }, per_page=#{ per_page }")

    companyList = Company.includes(:employee).order('id': 'asc').offset((page-1) * per_page).limit(per_page)

    total_count = Company.count
    total_page = total_count % per_page == 0 ? total_count / per_page : total_count / per_page + 1
    data = companyList.map{ |company| format_company(company) }

    {
      data: data,
      total_count: total_count,
      page: page,
      per_page: per_page,
      total_page: total_page
    }
  end

  # 对model进行处理，过滤不需要的字段
  # 目前不知道其他方法，先手动处理
  def self.format_company(company)
    return {} if company.blank?
    {
      id: company.id,
      name: company.name,
      followup_employee: (company.employee.emp_name_cn if company.employee.present?),
      phone_no: company.phone_no,
      postal_code: company.postal_code,
      address: company.address,
      followup_employee_code:company.followup_employee_code
    }
  end

  # 更新公司信息
  def self.update(json)
    record = Company.find_by('id': json[:id])
    return false if record.blank?

    record.name = json[:name]
    record.phone_no = json[:phone_no]
    record.postal_code = json[:postal_code]
    record.address = json[:address]
    record.followup_employee_code = json[:followup_employee_code]

    record.save
  end

  # 根据id删除公司记录
  def self.delete_by_id(id)
    Company.where('id': id).destroy_all
  end

end